<?php
declare (strict_types = 1);

namespace app\patient\controller;
use app\AppAuthController;
use app\Db2;
use Lop\LopOpensdkPhp\Filters\ErrorResponseFilter;
use Lop\LopOpensdkPhp\Filters\IsvFilter;
use Lop\LopOpensdkPhp\Options;
use Lop\LopOpensdkPhp\Support\DefaultClient;
use Lop\LopOpensdkPhp\Support\GenericRequest;
class Jd{
    /**
     * @Notes: 计算签名1
     * @Interface sign
     * @param $algorithm // 计算方式
     * @param $data // content
     * @param $secret // app_secret
     * @return string
     * @author: Shaco
     * @Time: 2022/10/22-14:10
     */
    private function sign($algorithm, $data, $secret)
    {
        if ($algorithm == "md5-salt") {
            return md5($data);
        } else if ($algorithm == "HMacMD5") {
            return base64_encode(hash_hmac("md5", $data, $secret, true));
        } else if ($algorithm == "HMacSHA1") {
            return base64_encode(hash_hmac("sha1", $data, $secret, true));
        } else if ($algorithm == "HMacSHA256") {
            return base64_encode(hash_hmac("sha256", $data, $secret, true));
        } else if ($algorithm == "HMacSHA512") {
            return base64_encode(hash_hmac("sha512", $data, $secret, true));
        }
        throw new Exception("Algorithm " . $algorithm . " not supported yet");
    }

    /**
     * @Notes: 京东下单
     * @Interface jdSend
     * @author: Shaco
     * @Time: 2022/10/22-09:11
     */
    private function jdSend($body,$pathIn){
        // 域名
        $baseUrl = "https://test-api.jdl.cn";
        // app_key
        $appKey = "19a6a2043fbb47aab02f486bef654ab7";
        // app_secret
        $appSecret = "bafbc6db027d496da35dcb7b5d8ade59";
        // access_token
        $accessToken = "96c416d624ec435696412e008c897470";
        // LOP-DN 对接方案编码
        $domain = "express";
        // 请求地址
        $path = $pathIn;
        // 计算签名方式
        $algorithm="md5-salt";
        // 调用时间
        $timestamp = date("Y-m-d H:i:s");
        // 请求方法
        $method = "POST";

        // 请求体  需要json字符串格式
        $BODY = json_encode($body,JSON_UNESCAPED_UNICODE);

        // 计算签名
        $content = $appSecret."access_token".$accessToken."app_key".$appKey."method".$path."param_json".$BODY."timestamp".$timestamp."v"."2.0".$appSecret;
        $sign = $this->sign($algorithm, $content, $appSecret);


        // 构建请求头
        $offset = strval(date("Z") / 3600);
        $headers = array(
            "lop-tz" => $offset,
            "Content-Type" => "application/json;charset=utf-8"
        );

        // 构建请求地址上的query参数
        $query = http_build_query(array(
            "LOP-DN" => $domain,
            "app_key" => $appKey,
            "access_token" => $accessToken,
            "timestamp" => $timestamp,
            "v" => "2.0",
            "sign" => $sign,
            "algorithm" => $algorithm
        ));

        $uri = $baseUrl.$path."?".$query;

        $content = stream_context_create(array(
           "http" => array(
                "method"=> $method,
                "header" => $headers,
                "content" => $BODY,
                "user_agent" => "lop-http/php"
           )
        ));

        $response = @file_get_contents($uri,true,$content);
        /**
         * 如果返回结果正确 则 需要将物流单号存到表中
         */
        return $response;
        //        if($response) {
        //            echo $response . PHP_EOL;
        //        }else{
        //            echo error_get_last()['message'].PHP_EOL;
        //        }
    }

    /**
     * @Notes: 外部调用的下单接口
     * @Interface jdReceiveOrder
     * @author: Shaco
     * @Time: 2022/10/22-14:44
     */
    public function jdReceiveOrder(){
        $body = [
            [
                "customerCode" => "27K1234912",  // *
                "salePlat" => "0030001",  // *
                "orderId" => "0878cff1c5324ee5b893b55d843fdcc8",  // * 自己的订单号

                "receiveAddress" => "北京市北京市朝阳区三间房镇建国路20号中国传媒大学梆子井公寓",  // * 收件人地址
                "receiveMobile" => "13111111111",  // 收件人电话
                "receiveName" => "纪君奕",  // * 收件人姓名
                "senderAddress" => "北京市石景山区八角街道璟公院10号楼@1#39#石景山站#1",  // * 寄件人地址
                "senderMobile" => "13111111111",   // 寄件人电话
                "senderName" => "京诚电商（ZER）",  // * 寄件人姓名
                "packageCount" => 1,  // * 包裹数量
                "promiseTimeType" => 1,  // * 产品类型 1是特惠送
                "weight" => 1, // * 重量
                "goodsDtoList" => [  // 商品详细信息
                    [
                        "productCount" => 1,  // 数量
                        "productName" => "一双鞋"  // 名字
                    ]
                ]
            ]
        ];
        $path = "/WaybillJosService/receiveOrderInfo";

        $res = $this->jdSend($body,$path);

        print_r($res);
        // 继续写获取到物流信息后的订单流程
    }

    /**
     * @Notes: 查询物流信息
     * @Interface jdSearchInfo
     * @author: Shaco
     * @Time: 2022/10/22-14:52
     */
    public function jdSearchInfo(){
        $body = array(
            "customerCode" => "27K1234912",
            "waybillCode" => "JDVE00045680187",
            "josPin" => "pin"
        );

        $path = "/query/dynamictraceinfo";

        $res = $this->jdSend($body,$path);

        print_r($res);
    }
}
